package com.jzlin.alltools.utils;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * Ip工具类.
 *
 * @author linjz
 * @date 2024/9/13
 */
@Slf4j
public class IpUtils {
    /**
     * 获取客户端请求真实ip
     * @param request
     * @return
     */
    public static String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 如果有多个 IP，返回第一个
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0].trim();
        }
        return ip;
    }

    /**
     * 判断给定的字符串是否为有效的 IP 地址
     *
     * @param ipAddress 待验证的 IP 地址
     * @return 如果是有效的 IP 地址，则返回 true；否则返回 false
     */
    public static boolean isValidIP(String ipAddress) {
        if (ipAddress == null || ipAddress.isEmpty()) {
            return false;
        }
        try {
            InetAddress inetAddress = InetAddress.getByName(ipAddress);
            return inetAddress.getHostAddress().equals(ipAddress);
        } catch (UnknownHostException e) {
            return false;
        }
    }

    /**
     * 是否内网ip
     * @param ip
     * @return
     */
    public static boolean isInternalIp(String ip) {
        // 检查是否为内网IP（IPv4）
        if (ip.startsWith("10.") || ip.startsWith("172.") || ip.startsWith("192.168.") || ip.startsWith("127")  || ip.startsWith("0")) {
            return true;
        }

        // 检查是否为内网IP（IPv6）
        try {
            InetAddress address = InetAddress.getByName(ip);
            return address.isSiteLocalAddress(); // 判断是否为站点本地地址（内网IPv6）
        } catch (UnknownHostException e) {
            log.warn("无法解析IP地址: {}", ip, e);
            return false;
        }
    }
}
